package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.*;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private CacheClient cacheClient;
    @Override
    public Result queryById(Long id) throws InterruptedException {
//        互斥锁解决缓存击穿问题
//        return queryWithMutex(id);

//        逻辑过期解决缓存击穿问题
//        return queryWithLogicalExpire(id);
//
//        工具类实现缓存穿透
        Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
//        工具类实现缓存击穿
//        Shop shop = cacheClient.queryWithLogicalExpire(
//                CACHE_SHOP_KEY,LOCK_SHOP_KEY,id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        if (shop == null) {
            return Result.fail("店铺信息不存在");
        }
        return Result.ok(shop);
    }
    //互斥锁解决缓存击穿问题
    public Result queryWithMutex(Long id) throws InterruptedException {
        String key="cache:shop:" + id;
        String lockKey="lock:shop:"+id;
        do{
            String shopJson = stringRedisTemplate.opsForValue().get(key);
            if(StrUtil.isNotBlank(shopJson)){
                return Result.ok(JSONUtil.toBean(shopJson, Shop.class));
            }
            //解决缓存穿透
            if(shopJson!=null){
                return Result.fail("店铺不存在");
            }
            //获取互斥锁防止多线程查询数据库
            boolean success = getLock(lockKey);
            if(!success){
                Thread.sleep(50);
            }else break;
        }while (true);
        //获取锁后需检查缓存是否已经重建
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        if(StrUtil.isNotBlank(shopJson)){
            return Result.ok(JSONUtil.toBean(shopJson, Shop.class));
        }
        if(shopJson!=null){
            return Result.fail("店铺不存在");
        }
        //查询数据库
        Shop shop = getById(id);
        //模拟查询耗时
        Thread.sleep(200);
        if(shop == null){
            stringRedisTemplate.opsForValue().set(key,"",2, TimeUnit.MINUTES);
            return Result.fail("店铺不存在");
        }
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),30, TimeUnit.MINUTES);
        unLock(lockKey);
        return Result.ok(shop);
    }
    private static final ExecutorService CACHE_BUILD_EXECUTOR= Executors.newFixedThreadPool(10);
    public Result queryWithLogicalExpire(Long id) throws InterruptedException {
        String key=CACHE_SHOP_KEY + id;
        String lockKey=LOCK_SHOP_KEY +id;
        String redisDataJson = stringRedisTemplate.opsForValue().get(key);
        if(StrUtil.isBlank(redisDataJson)){
            return Result.fail("店铺不存在");
        }
        RedisData redisData = JSONUtil.toBean(redisDataJson, RedisData.class);
        LocalDateTime expire = redisData.getExpireTime();
        Shop shop= JSONUtil.toBean((JSONObject) redisData.getData(),Shop.class);
        if(expire.isAfter(LocalDateTime.now())){
            return Result.ok(shop);
        }
        //获取互斥锁
        boolean success = getLock(lockKey);
        if(success) {
            //获得锁后再次检测redis，做双重检测
            redisDataJson=stringRedisTemplate.opsForValue().get(key);
            if(StrUtil.isBlank(redisDataJson)){
                return Result.fail("店铺不存在");
            }
            redisData=JSONUtil.toBean(redisDataJson, RedisData.class);
            expire = redisData.getExpireTime();
            shop= JSONUtil.toBean((JSONObject) redisData.getData(),Shop.class);
            if(expire.isAfter(LocalDateTime.now())){
                return Result.ok(shop);
            }
            //开启独立线程进行缓存重建
            CACHE_BUILD_EXECUTOR.submit(()->{
                try {
                    saveShopToRedis(id,20L);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }finally {
                    //释放锁
                    unLock(lockKey);
                }
            });
        }
        //返回过期店铺信息
        return Result.ok(shop);
    }




    private boolean getLock(String key){
        Boolean b = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(b);
    }

    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }
    public void saveShopToRedis(Long id,Long expireSeconds) throws InterruptedException {
        Shop shop = getById(id);
        Thread.sleep(200);
        RedisData redisData=new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));
    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id==null)
            return Result.fail("店铺id不能为空");
        //更新数据库
        updateById(shop);
        //删除缓存
        String key="cache:shop:" + id;
        stringRedisTemplate.delete(key);
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        if(x==null||y==null){
            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }
        int from=(current-1)*SystemConstants.DEFAULT_PAGE_SIZE;
        int end=current*SystemConstants.DEFAULT_PAGE_SIZE;
        String key=SHOP_GEO_KEY+typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().radius(
                key, new Circle(x, y, 5000),
                RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().limit(end)
        );
        if (results == null) return Result.ok(Collections.emptyList());

        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();

        if(list.size()<=from) return Result.ok(Collections.emptyList());

        List<Long>ids=new ArrayList<>(SystemConstants.DEFAULT_PAGE_SIZE);
        Map<Long,Double> map=new HashMap<>(SystemConstants.DEFAULT_PAGE_SIZE);
        list.stream().skip(from).forEach(result->{
            String idStr = result.getContent().getName();
            ids.add(Long.valueOf(idStr));
            double distance = result.getDistance().getValue();
            map.put(Long.valueOf(idStr),distance);
        });
        String join = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("order by field(id," + join + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(map.get(shop.getId()));
        }
        return Result.ok(shops);
    }
}
